package com.psn.zjk.utils.nexus_uploader.utils;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public final class XMLUtils {

	//TODO 
	private static String encoding = "GBK";
	private static JAXBContext context;

	/** 序列化为4字节长度标志+XML字符串格式数据
	 * @throws JAXBException
	 * @throws XMLStreamException
	 * @throws UnsupportedEncodingException */
	public static String toXMLString(Object obj, Class<?> clazzes) throws XMLStreamException, JAXBException, UnsupportedEncodingException {
		context = JAXBContext.newInstance(clazzes);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// 注意jdk版本
		XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
		XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos, encoding);
		xmlStreamWriter.writeStartDocument(encoding, "1.0");
		marshaller.marshal(obj, xmlStreamWriter);
		xmlStreamWriter.writeEndDocument();
		xmlStreamWriter.close();
		return baos.toString(encoding);
	}

	/** XML转换为Socket接收对象
	 * @throws JAXBException
	 * @throws ParserConfigurationException
	 * @throws SAXException */
	@SuppressWarnings("unchecked")
	public static <T> T toJavaBean(String xml, Class<T> c) throws JAXBException, SAXException, ParserConfigurationException {
		T t = null;
		xml = xml.replaceAll("&oslash;", "").replaceAll("<!--[\\s\\S]*?-->", "").replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");
		JAXBContext context = JAXBContext.newInstance(c);
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		saxParserFactory.setNamespaceAware(false);
		XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader();
		Unmarshaller unmarshaller = context.createUnmarshaller();
		SAXSource saxSource = new SAXSource(xmlReader, new InputSource(new StringReader(xml)));
		t = (T) unmarshaller.unmarshal(saxSource);
		return t;
	}

}
